<?php

namespace openapi\controllers\base;

use openapi\models\out\ReponseResult;
use openapi\models\out\Error;

/**
 * 控制器-接口
 *
 * @author peng.huang
 */
class OpenAPIController extends \application\controllers\base\BaseController {

    /**
     * 令牌
     * 
     * @var string 
     */
    public $token;

    /**
     * 响应结果
     * 
     * @var ReponseResult 
     */
    protected $_reponseResult;

    /**
     * 初始化
     */
    public function init() {
        $this->_reponseResult = new ReponseResult();

        $isValid = $this->checkValid();
        if (!$isValid) {
            $this->isInterrupted = !$isValid;
            $this->response->setHeaders(array('Content-type' => 'text/json'));
            echo json_encode($this->_reponseResult);
        }
    }

    /**
     * 添加错误信息
     * 
     * @param string $message [信息]
     * @param int $code [代码值]
     * @return boolean
     */
    protected function _addError($message, $code = -1) {
        $err = new Error();
        $err->code = $code;
        $err->message = $message;

        $this->_reponseResult->result = 0;
        $this->_reponseResult->error = $err;
        return FALSE;
    }

    /**
     * 验证数据是否正确
     * 
     * @return boolean
     */
    private function checkValid() {
        // 判断是否POST
        if (!$this->request->isPost()) {
            return $this->_addError('不支持GET操作。');
        }

        return TRUE;
        $isRedisConnected = \Peng::$app->redis->isConnected;
        if ($isRedisConnected) {
            /* / 权限判断
              $auth = \Peng::$app->redis->hGet('tokenlist', $this->token);
              $isNoAuth = FALSE;
              if (!$auth) {
              $isNoAuth = TRUE;
              } elseif (!($auth = \Peng::$app->redis->get($this->token))) {
              $isNoAuth = TRUE;
              }

              if ($isNoAuth) {
              $this->formatOutput(FALSE, array(), '抱歉，您没有权限~', $this->format);
              }
             */
            // 限制操作频率
            $sid = session_id();
            if (empty($sid)) {
                session_start();
                $sid = session_id();
            }

            $quick = \Peng::$app->redis->get($sid);
            if (!$quick) {
                \Peng::$app->redis->save($sid, 1, 60);
            } else {
                return $this->_addError('您操作太快，喝杯咖啡，稍微休息一下。');
            }
        }

        return TRUE;
    }

}
